package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SeckillService {
    @Autowired
    private RedisTemplate<String, Object> cacheRedisTemplate;

    @Autowired
    private RedisScript<Long> stockDeductionScript;

    public SeckillService(RedisTemplate<String, Object> redisTemplate) {
        this.cacheRedisTemplate = redisTemplate;
    }

    /**
     * 执行秒杀操作
     */
    public SeckillResult doSeckill(String productId, int quantity) {
        String stockKey = "seckill:stock:" + productId;

//        DefaultRedisScript<String> redisScript = new DefaultRedisScript<>();
//        redisScript.setScriptText(getSeckillLuaScript());
//        redisScript.setResultType(String.class);

        List<String> keys = Arrays.asList(stockKey);

        try {
            Long result = cacheRedisTemplate.execute(stockDeductionScript, keys, quantity);

            if (1==result) {
                return new SeckillResult(true, "秒杀成功", productId, quantity);
            } else {
                return new SeckillResult(false, "库存不足", productId, quantity);
            }
        } catch (Exception e) {
            return new SeckillResult(false, "系统异常: " + e.getMessage(), productId, quantity);
        }
    }

    /**
     * 初始化商品库存
     */
    public void initProductStock(String productId, int stock) {
        String stockKey = "seckill:stock:" + productId;
        cacheRedisTemplate.opsForValue().set(stockKey, String.valueOf(stock));
    }

    /**
     * 获取商品库存
     */
    public Integer getProductStock(String productId) {
        String stockKey = "seckill:stock:" + productId;
        String stockStr = (String) cacheRedisTemplate.opsForValue().get(stockKey);
        return stockStr != null ? Integer.parseInt(stockStr) : null;
    }

    /**
     * 秒杀结果类
     */
    public static class SeckillResult {
        private boolean success;
        private String message;
        private String productId;
        private int quantity;

        public SeckillResult(boolean success, String message, String productId, int quantity) {
            this.success = success;
            this.message = message;
            this.productId = productId;
            this.quantity = quantity;
        }

        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public String getProductId() { return productId; }
        public int getQuantity() { return quantity; }
    }
}
